package com.pudu.mydemo.fragment;

import android.app.Dialog;
import android.app.DialogFragment;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.ScatterChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.BubbleData;
import com.github.mikephil.charting.data.BubbleDataSet;
import com.github.mikephil.charting.data.BubbleEntry;
import com.github.mikephil.charting.data.CandleData;
import com.github.mikephil.charting.data.CandleDataSet;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.ScatterData;
import com.github.mikephil.charting.data.ScatterDataSet;
import com.github.mikephil.charting.highlight.Highlight;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.interfaces.datasets.IScatterDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.pudu.json.MapDecode;
import com.pudu.mydemo.entity.MapData;
import com.pudu.mydemo.entity.Point;
import com.pudu.pdrobot.App;
import com.pudutech.pdrobot.R;

import org.json.JSONException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

/**
 * Created by guiliu on 2016/8/23.
 */
public class DiagramFragment extends DialogFragment implements OnChartValueSelectedListener {
    private CombinedChart mChart;
    private  MapDecode mapDecode;
    private float minX ,maxX,minY,maxY,max,min;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (getDialog() != null) {
            getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        View v = inflater.inflate(R.layout.fragment_diagram_combine,null);
        docode();
        mChart = (CombinedChart) v.findViewById(R.id.chart1);
        mChart.setDescription("");
        mChart.setBackgroundColor(Color.WHITE);
        mChart.setDrawGridBackground(false);
        mChart.setDrawBarShadow(false);
        mChart.setHighlightFullBarEnabled(false);
        // draw bars behind lines
        mChart.setDrawOrder(new CombinedChart.DrawOrder[]{
                CombinedChart.DrawOrder.BAR, CombinedChart.DrawOrder.BUBBLE, CombinedChart.DrawOrder.CANDLE, CombinedChart.DrawOrder.LINE, CombinedChart.DrawOrder.SCATTER
        });

        Legend l = mChart.getLegend();
        l.setWordWrapEnabled(true);
        l.setPosition(Legend.LegendPosition.BELOW_CHART_CENTER);
        mChart.setScaleEnabled(true);
        mChart.setPinchZoom(true);  //设置x轴和y轴能否同时缩放。默认是否
//        YAxis rightAxis = mChart.getAxisRight();
//        rightAxis.setDrawGridLines(false);
//        rightAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

//        YAxis leftAxis = mChart.getAxisLeft();
//        leftAxis.setDrawGridLines(false);
//        leftAxis.setAxisMinimum(0f); // this replaces setStartAtZero(true)

//        XAxis xAxis = mChart.getXAxis();
//        xAxis.setPosition(XAxis.XAxisPosition.BOTH_SIDED);
//        xAxis.setAxisMinimum(0f);
//        xAxis.setGranularity(1f);
        //设置x轴的样式
        XAxis xAxis = mChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisLineColor(Color.parseColor("#66CDAA"));

        xAxis.setDrawGridLines(false);
        xAxis.setAxisMinValue(min);
//        xAxis.setAxisLineWidth(1);
        xAxis.setAxisMaxValue(max);
        xAxis.setLabelCount((int)Math.abs(max - min));
        //设置是否显示x轴
        xAxis.setEnabled(true);
//        xAxis.setGranularityEnabled(true);
//        xAxis.setGranularity(1f);
        //设置左边y轴的样式
        YAxis yAxisLeft = mChart.getAxisLeft();
        yAxisLeft.setAxisLineColor(Color.parseColor("#66CDAA"));

        yAxisLeft.setDrawGridLines(false);
        yAxisLeft.setAxisMinValue(min);
//        yAxisLeft.setAxisLineWidth(1);
        yAxisLeft.setAxisMaxValue(max);
        yAxisLeft.setGranularityEnabled(true);
        yAxisLeft.setGranularity(1f);
        //设置右边y轴的样式
        yAxisLeft.setLabelCount((int)Math.abs(max - min));
        YAxis yAxisRight = mChart.getAxisRight();
        yAxisRight.setEnabled(false);

//        mChart.zoom(2.0f,2.0f,0f,0f);
       /* xAxis.setValueFormatter(new IAxisValueFormatter() {
            @Override
            public String getFormattedValue(float value, AxisBase axis) {
                return mMonths[(int) value % mMonths.length];
            }

            @Override
            public int getDecimalDigits() {
                return 0;
            }
        });*/
//        this.mAxisMinimum = min;
//        this.mAxisMaximum = max;
//        this.mAxisRange = Math.abs(max - min);

        Log.e("Diag","xAxis.getAxisMinimum():"+xAxis.getAxisMinimum()+" xAxis.getAxisMinimum()"+xAxis.getAxisMaximum()+"w:"+xAxis.getGranularity());
        CombinedData data = new CombinedData();

        data.setData(generateLineData());
//        data.setData(generateBarData());
//        data.setData(generateBubbleData());
        data.setData(generateScatterData());
        data.setData(generateScatterTargetData());
//        data.setData(generateCandleData());
//        data.setValueTypeface(mTfLight);

//        xAxis.setAxisMaximum(data.getXMax() + 0.25f);

        mChart.setData(data);
        mChart.invalidate();
        return v;
    }


    public void docode() {
        mapDecode = new MapDecode();
        try {
            String mapString =App.getInstance().getApplicationAtlasData()/*MapData.map*/;
            if(mapString != null) {
                mapDecode.decode(mapString);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        ArrayList<Point> points = (ArrayList<Point>)mapDecode.getUwbList();
        ArrayList<Point> points = (ArrayList<Point>) mapDecode.getTrackList();
        ArrayList<Point> points1 = (ArrayList<Point>)mapDecode.getTargetList();
        ArrayList<Point> points2 = (ArrayList<Point>)mapDecode.getUwbList();
        ArrayList<Float> X = new ArrayList<>();
        ArrayList<Float> Y = new ArrayList<>();
        if(points == null || points1 == null || points2== null) return;
        for(int i=0; i<points.size(); i++) {
            X.add(points.get(i).getStartX());
            X.add(points.get(i).getEndX());
            Y.add(points.get(i).getStartY());
            Y.add(points.get(i).getEndY());
        }

        for(int i=0; i<points1.size(); i++) {
            X.add(points1.get(i).getStartX());
            X.add(points1.get(i).getEndX());
            Y.add(points1.get(i).getStartY());
            Y.add(points1.get(i).getEndY());
        }

        for(int i=0; i<points2.size(); i++) {
            X.add(points2.get(i).getStartX());
            X.add(points2.get(i).getEndX());
            Y.add(points2.get(i).getStartY());
            Y.add(points2.get(i).getEndY());
        }

        Collections.sort(X);
        Collections.sort(Y);
        minX = X.get(0);
        maxX = X.get(X.size()-1);
        minY = Y.get(0);
        maxY = Y.get(Y.size()-1);
        if(minX <= minY) {
            min = minX;
        }else {
            min = minY;
        }

        if(maxX <= maxY) {
            max = maxY;
        }else{
            max = maxX;
        }
        min = min -1;max = max+1;
        Log.e("Diag","min: "+min+" max: "+max);
    }

    public ScatterData generateScatterData() {
        MapDecode mapDecode = new MapDecode();
        try {
            String mapString = App.getInstance().getApplicationAtlasData()/*MapData.map*/;
            if(mapString != null) {
                mapDecode.decode(mapString);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ArrayList<Point> points = (ArrayList<Point>)mapDecode.getUwbList();
        if(points == null) return null;
        ArrayList<Entry> yVals = new ArrayList<Entry>();
       for(int i=0; i<points.size(); i++) {
           yVals.add(new Entry((points.get(i).getStartX() ), (points.get(i).getStartY())));
       }
        ScatterDataSet set = new ScatterDataSet(yVals, "DS 0");
        set.setScatterShape(ScatterChart.ScatterShape.SQUARE);
//        set.setColor(ColorTemplate.COLORFUL_COLORS[0]);
        set.setColors(ColorTemplate.MATERIAL_COLORS);
        set.setScatterShapeSize(7.5f);
        set.setDrawValues(false);
        set.setValueTextSize(10f);
        set.setScatterShapeSize(8f);
        ArrayList<IScatterDataSet> dataSets = new ArrayList<IScatterDataSet>();
        dataSets.add(set);
        // create a data object with the datasets
        ScatterData data = new ScatterData(dataSets);
       return data;
    }


    public ScatterData generateScatterTargetData() {
        MapDecode mapDecode = new MapDecode();
        try {
            String mapString = App.getInstance().getApplicationAtlasData()/*MapData.map*/;
            if(mapString != null) {
                mapDecode.decode(mapString);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ArrayList<Point> points = (ArrayList<Point>)mapDecode.getTargetList();
        ArrayList<Point> points2 = (ArrayList<Point>)mapDecode.getUwbList();
        if(points == null) return null;
        ArrayList<Entry> yVals = new ArrayList<Entry>();
        for(int i=0; i<points.size(); i++) {
            yVals.add(new Entry((points.get(i).getStartX() ), (points.get(i).getStartY())));
        }
        for(int i=0; i<points2.size(); i++) {
            yVals.add(new Entry((points2.get(i).getStartX() ), (points2.get(i).getStartY())));
        }
        ScatterDataSet set = new ScatterDataSet(yVals, "DS 0");
        set.setScatterShape(ScatterChart.ScatterShape.SQUARE);
//        set.setColor(ColorTemplate.COLORFUL_COLORS[0]);
        set.setColors(ColorTemplate.MATERIAL_COLORS);
        set.setScatterShapeSize(7.5f);
        set.setDrawValues(false);
        set.setValueTextSize(10f);
        set.setScatterShapeSize(8f);
        ArrayList<IScatterDataSet> dataSets = new ArrayList<IScatterDataSet>();
        dataSets.add(set);
        // create a data object with the datasets
        ScatterData data = new ScatterData(dataSets);
        return data;
    }

    public LineData generateLineData() {
        MapDecode mapDecode = new MapDecode();
        try {
            String mapString = App.getInstance().getApplicationAtlasData()/*MapData.map*/;
            if(mapString != null) {
                mapDecode.decode(mapString);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        ArrayList<Point> points = (ArrayList<Point>) mapDecode.getTrackList();
        if(points == null) return null;
        ArrayList<ILineDataSet> dataSets = new ArrayList<ILineDataSet>();
        for (int z = 0; z < points.size(); z++) {
            ArrayList<Entry> values = getEntryList(points.get(z));
            LineDataSet set = new LineDataSet(values, "DataSet " + (z + 1));
            set.setLineWidth(2.5f);
            set.setCircleRadius(4f);
            int color = mColors[z % mColors.length];
            set.setColor(color);
            set.setCircleColor(color);

//            set.setColor(Color.rgb(240, 238, 70));
//            set.setLineWidth(2.5f);
//            set.setCircleColor(Color.rgb(240, 238, 70));
//            set.setCircleRadius(5f);
//            set.setFillColor(Color.rgb(240, 238, 70));
//            set.setMode(LineDataSet.Mode.CUBIC_BEZIER);
//            set.setDrawValues(true);
//            set.setValueTextSize(10f);
//            set.setValueTextColor(Color.rgb(240, 238, 70));

            set.setAxisDependency(YAxis.AxisDependency.LEFT);
            dataSets.add(set);
        }

        ((LineDataSet) dataSets.get(0)).enableDashedLine(10, 10, 0);
        ((LineDataSet) dataSets.get(0)).setColors(ColorTemplate.VORDIPLOM_COLORS);
        ((LineDataSet) dataSets.get(0)).setCircleColors(ColorTemplate.VORDIPLOM_COLORS);

        LineData data = new LineData(dataSets);

        return data;
    }

    private int[] mColors = new int[] {
            ColorTemplate.VORDIPLOM_COLORS[0],
            ColorTemplate.VORDIPLOM_COLORS[1],
            ColorTemplate.VORDIPLOM_COLORS[2]
    };


    public ArrayList<Entry> getEntryList(Point point) {
        ArrayList<Entry> values = new ArrayList<Entry>();
        values.add(new Entry(point.getStartX(), point.getStartY()));
        values.add(new Entry(point.getEndX(), point.getEndY()) );
        Log.e("Diag","startx:"+point.getStartX() +" startY:"+point.getStartY()+" endx:"+point.getEndX()+" endy:"+point.getEndY());
        return values;
    }




    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Dialog dialog = getDialog();
        if (dialog != null) {
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            dialog.getWindow().setLayout((int) (dm.heightPixels * 0.9), (int) (dm.heightPixels * 0.9));
        }
    }

    @Override
    public void onValueSelected(Entry e, Highlight h) {

    }

    @Override
    public void onNothingSelected() {

    }
}
